package com.wxx.maker.generator;

import cn.hutool.core.io.FileUtil;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

/**
 * 启动脚本对应的生成器
 */
public class ScriptGenerator {

    public static void doGenerate(String outputPath, String jarPath) {
        // Linux脚本
        StringBuffer sb = new StringBuffer();
        //#!/bin/bash
        //java -jar target/you-generator-basic-1.0-SNAPSHOT-jar-with-dependencies.jar "$@"
        sb.append("#!/bin/bash").append("\n");
        sb.append(String.format("java -jar %s \"$@\"", jarPath)).append("\n");
        FileUtil.writeBytes(sb.toString().getBytes(StandardCharsets.UTF_8), outputPath);
        // 添加可执行权限(Windows默认有权限)
        try{
            Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrwxrwx"); // 个人用户本机用户远程用户
            Files.setPosixFilePermissions(Paths.get(outputPath), permissions);
        }catch (Exception e){

        }

        // Windows脚本
        sb = new StringBuffer();
        //@echo off
        //java -jar target/you-generator-basic-1.0-SNAPSHOT-jar-with-dependencies.jar %*
        sb.append("@echo off").append("\n");
        sb.append(String.format("java -jar %s %%*", jarPath)).append("\n");
        FileUtil.writeBytes(sb.toString().getBytes(StandardCharsets.UTF_8), outputPath + ".bat");
    }

}
